import {
    APPKEY,
    COOKIE_VALUE,
    httpUrl,
    OS,
    PSESSIONID,
    TIME,
    TTID,
    UUID,
    MUID,
    SIGN,
    TOKEN
} from "./constant";
import Store from "./store";
import {getReq} from "./request";

import getSign = require("./sign.js")
type Env = "search" | "rateList"

interface paramsCfg {
    env: Env,
    params: any,

    [propsName: string]: any
}

const presetCfg = function (config: paramsCfg) {
    return {
        search: {
            data: {
                cKey: "pc-home-slices",
                page: 1,
                [COOKIE_VALUE]: Store.get(COOKIE_VALUE),
                [PSESSIONID]: Store.get(PSESSIONID),
                ...config.params
            },
            [TTID]: "NMMain@mgj_pc_10.0",
            version: "22",
            api: "mwp.pagani.search"
        },
        rateList: {
            data: {
                "pageSize": "20",
                "sort": 1,
                "isNewDetail": 1,
                "page": 1,
                "type": 1,
                "marketType": "market_mogujie",
                "clientType": "pc",
                ...config.params
            },
            [TTID]: "NMMain@mgj_pc_1.0",
            version: "v2",
            api: "mwp.RateWeb.pc.rate.ratelist"

        }
    }[config.env]
}


export const getQueryParams = async function (config: paramsCfg) {
    let preset = presetCfg(config);
    const params = {
        [APPKEY]: "100028",
        [OS]: "unknown",
        [TIME]: Date.now(),
        [TTID]: preset[TTID],
        [MUID]: await getUUID(),
        data: preset.data,
        ['callback']: "mwpCb1"
    }
    let signData = {
        headers: params,
        data: params.data,
        token: Store.get(TOKEN),
        api: preset.api,
        version: preset.version
    }
    return {...params, [SIGN]: getSign(signData)};
}

// 获取uuid
const getUUID = async function (): Promise<string | number> {
    if (!Store.get(UUID)) {
        await getReq(httpUrl.getUUID);
    }
    return Store.get(UUID);
}

